package cn.ayanami.blog.article.controller;

import java.util.List;

import io.swagger.v3.oas.annotations.Operation;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import cn.ayanami.blog.article.entity.dto.AddArticleDto;
import cn.ayanami.blog.article.entity.dto.ModifyArticleDto;
import cn.ayanami.blog.article.entity.vo.ArticleListVo;
import cn.ayanami.blog.article.entity.vo.ArticleVo;
import cn.ayanami.blog.article.service.ArticleService;
import cn.ayanami.blog.system.bean.Result;
import reactor.core.publisher.Mono;

/**
 * 文章管理
 */
@RestController
@RequestMapping(value = "article")
@CrossOrigin(origins = "*",maxAge = 3600)
public class ArticleController {

    private final ArticleService articleService;

    public ArticleController(ArticleService articleService) {
        this.articleService = articleService;
    }

    @Operation(summary = "获取指定ID的文章文本")
    @GetMapping("/getArticle")
    public Mono<Result<ArticleVo>> getArticleById(@RequestParam String articleId) {
        return articleService.getArticleByArticleId(articleId).mapNotNull(Result::OK)
                .defaultIfEmpty(Result.error(101, "文章不存在或已删除"))// 无文章ID的查询结果是时返回默认Result
        ;
    }

    @Operation(summary = "获取文章列表")
    @GetMapping("/getArticleList")
    public Mono<Result<List<ArticleListVo>>> getArticleList(Integer page, Integer size) {
        if(page==null||page<0){
            page=0;
        }
        if(size==null||size<1){
            size=10;
        }
        var res = articleService.getArticleList(page, size).collectList();

        return res.map(Result::OK);
    }


    @Operation(summary = "添加文章")
    @PostMapping("/addArticle")
    public Mono<Result<?>> addArticle(@RequestBody AddArticleDto addArticleDto) {
//        if (error.hasErrors()) {
//            return Mono.just(Result.validateError(error.getAllErrors()));
//        } 
        var result = articleService.addArticle(addArticleDto);
        return result.mapNotNull(i -> Result.OK(String.valueOf(1)));
    }

    @Operation(summary = "添加文章")
    @PostMapping("/modifyArticle")
    public Mono<Result<?>> modifyArticle(@RequestBody ModifyArticleDto modifyArticleDto, BindingResult error) {
        if (error.hasErrors()) {
            return Mono.just(Result.validateError(error.getAllErrors()));
        }
        var result = articleService.modifyArticle(modifyArticleDto);
        return result.mapNotNull(i -> Result.OK(String.valueOf(i)));
    }

}
